package com.relife.sys.service;

import java.io.File;
import java.io.IOException;

import com.relife.common.file.FileUtil;
import com.relife.common.file.ImageUtil;
import com.relife.common.file.OpenOfficeUtil;
import com.relife.common.http.HttpUtil;
import com.relife.common.utils.DateUtil;
import com.relife.common.utils.ReflectUtil;
import com.relife.common.utils.StringUtil;
import com.relife.core.entity.FileEntity;
import com.relife.core.service.BaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



@Service
@Transactional
public class FileService extends BaseService {

	/**
	 * 上传文件
	 * 
	 * @author WU
	 * @date 2016年8月10日 下午4:20:20
	 * @param file
	 * @throws IOException
	 */
	public void upload(FileEntity file, String realPath) throws Exception {
		String addPath = "upload/" + DateUtil.getTime(DateUtil.YEAR) + "/" + DateUtil.getTime(DateUtil.MONTH) + "/";
		File f = new File(realPath + addPath);
		if (!f.exists()) {
			f.mkdirs();// 创建根目录
		}
		file.setFileSize(file.getFile().getSize());
		file.setSuffix(file.getFileSuffix());
		file.setName(file.getFile().getOriginalFilename());
		file.setPath(addPath + file.getFileName() + "." + file.getSuffix());

		if (FileEntity.IMAGE.equals(file.getDir())) {
			if (file.getWidth() != null) {
				ImageUtil.compressPicMaxWidth(file.getFile().getInputStream(), realPath + file.getPath(), file.getWidth());
			} else {
				ImageUtil.compressPic(file.getFile().getInputStream(), realPath + file.getPath());
			}
		} else if (FileEntity.FILE.equals(file.getDir())) {
			FileUtil.cotyFile(file.getFile().getInputStream(), realPath + file.getPath());
			if (OpenOfficeUtil.is2Pdf(file.getSuffix())) {
				file.setPdfPath(file.getPath().replace("." + file.getSuffix(), ".pdf"));
				OpenOfficeUtil.office2Pdf(realPath + file.getPath(), realPath + file.getPdfPath());
			}
		}
		this.save(file);
	}

	/**
	 * 删除文件
	 * 
	 * @author WU
	 * @date 2016年8月10日 下午4:20:44
	 * @param id
	 * @throws Exception
	 */
	public <T> void delFile(String id, String entityName) throws Exception {
		if (StringUtil.isNotEmpty(entityName)) {
			T t = this.getByHql("from " + entityName + " where id=:id", id);
			if (t != null) {
				FileEntity file = (FileEntity) ReflectUtil.getValue(t, "file");
				if (file != null) {
					String path = HttpUtil.getSession().getServletContext().getRealPath("/");
					File f = new File(path + file.getPath());
					if (f.exists()) {
						f.delete();
					}
					this.delete(t);
					this.delete(file);
				}
			}

		} else {
			FileEntity file = this.get(FileEntity.class, id);
			if (file != null) {
				String path = HttpUtil.getSession().getServletContext().getRealPath("/");
				File f = new File(path + file.getPath());
				if (f.exists()) {
					f.delete();
				}
				this.delete(file);
			}
		}
	}
}
